//
//  SEMessageViewController.swift
//  SmartEyeForPatient
//
//  Created by QDSG on 2021/4/16.
//

import UIKit

class SEMessageViewController: SEBaseViewController {

    private var viewModel = SEInquiryInfoViewModel()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        viewModel.decodeMessages()
        viewModel.updateData = { [weak self, viewModel] status in
            self?.refreshIndicator.animating = false
            self?.tableView.se_empty?.allowShow = true
            switch status {
            case .success:
                self?.tabBarItem.badgeValue = viewModel.messageCount
                self?.tableView.reloadData()
            case .auth:
                self?.presentLoginViewController(selector: #selector(self?.loadData))
            case .failure(let msg):
                SEHUD.showError(message: msg)
            }
        }
        
        SEIMManager.shared.pushMessageHandler = { model in
            switch model.cmd {
            case SEChatCMD.message.rawValue:
                self.loadData()
            case SEChatCMD.inquiryStatusChanged.rawValue:
                if model.status == .rejected ||
                    model.status == .confirming {
                    self.loadData()
                }
            default:
                break
            }
        }
    }
    
    override func setupNavBar() {
        super.setupNavBar()
        refreshIndicator.title = navigationItem.title
        navigationItem.titleView = refreshIndicator
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        loadData()
    }
    
    override func didBecomeActive() {
        if inCurrentVC { loadData() }
    }
    
    private lazy var refreshIndicator = SERefreshIndicator(frame: CGRect(x: 0, y: 0, width: 200, height: 44))

    @IBOutlet private weak var tableView: UITableView! {
        didSet {
            tableView.backgroundColor = .background
            tableView.tableFooterView = UIView()
            tableView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: UIScreen.bottomSafeHeight, right: 0)
            tableView.estimatedRowHeight = 44
            tableView.rowHeight = UITableView.automaticDimension
            
            tableView.se_empty = SEEmptyView { [weak self] in self?.loadData() }
            
            tableView.register(SEMessageInquiryCell.nibForCell(),
                               forCellReuseIdentifier: SEMessageInquiryCell.reuseIdentifier())
            tableView.register(SEMessageSystemCell.nibForCell(),
                               forCellReuseIdentifier: SEMessageSystemCell.reuseIdentifier())
        }
    }
}

extension SEMessageViewController {
    @objc private func loadData() {
        refreshIndicator.animating = true
        viewModel.getListOfInquiryMessages()
    }
    
    private func pushToChatVc(_ vm: SEInquiryInfoViewModel) {
        let chatVc = SEChatViewController(infoViewModel: vm)
        chatVc.title = vm.info.receiverName
        navigationController?.pushViewController(chatVc, animated: true)
    }
}

// MARK: - UITableViewDataSource

extension SEMessageViewController: UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return viewModel.numberOfRows
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        switch indexPath.section {
        case 0:
            let cell = tableView.dequeueReusableCell(withIdentifier: SEMessageInquiryCell.reuseIdentifier()) as! SEMessageInquiryCell
            let vm = viewModel.viewModel(at: indexPath)
            cell.update(with: vm)
            return cell
        case 1:
            let cell = tableView.dequeueReusableCell(withIdentifier: SEMessageSystemCell.reuseIdentifier()) as! SEMessageSystemCell
            cell.update(with: nil)
            return cell
        default:
            return UITableViewCell()
        }
    }
}

// MARK: - UITableViewDelegate

extension SEMessageViewController: UITableViewDelegate {
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let header = UINib.loadViewFrom(SEMessageSectionHeader.self)
        header.update(section: section)
        return header
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        let footer = UIView()
        footer.backgroundColor = .clear
        return footer
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 57
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 10
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: false)
        switch indexPath.section {
        case 0:
            let vm = viewModel.viewModel(at: indexPath)
            pushToChatVc(vm)
        default:
            break
        }
    }
}
